<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="订单编号" prop="orderCode">
        <el-select v-model="queryParams.orderId" filterable remote reserve-keyword placeholder="请输入订单编号"
                   :remote-method="searchOrder" :loading="orderLoading" clearable>
          <el-option v-for="item in orderList" :key="item.code" :label="item.code" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="customerId">
        <el-select v-model="queryParams.customerId" filterable remote reserve-keyword placeholder="请输入客户名称"
                   :remote-method="searchCustomer" :loading="customerLoading" clearable>
          <el-option v-for="item in customerList" :key="item.code" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="金额" prop="money">
        <el-input v-model="queryParams.money" placeholder="请输入金额"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['develop:FinanceInvoiceReceipt:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini"
                   @click="handleExport" v-hasPermi="['develop:FinanceInvoiceReceipt:export']">导出
        </el-button>
        <el-button type="success" icon="el-icon-upload2" size="mini"
                   @click="showUploadDialog">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
              :max-height="tableMaxHeight">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="客户名称" align="center" width="350" prop="customerName"/>
      <el-table-column label="订单编号" align="center" width="350" prop="orderCode"/>
      <el-table-column label="金额" align="center" prop="money"/>
      <el-table-column label="核销方式" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.finance_receipt_way" :value="scope.row.way"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.finance_receipt_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-attract" v-show="scope.row.status==='0'"
                     @click="handleWriteOff(scope.row)" v-hasPermi="['develop:FinanceInvoiceReceipt:edit']">核销
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-edit" v-show="scope.row.status==='0'"
                     @click="handleUpdate(scope.row)" v-hasPermi="['develop:FinanceInvoiceReceipt:edit']">修改
          </el-button>
          <el-popconfirm :title="`确认删除当前数据项？`" @confirm="handleDelete(scope.row)" v-show="scope.row.status==='0'"
                         style="margin-left: 10px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"
                       v-hasPermi="['develop:FinanceInvoiceReceipt:remove']">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <financeInvoiceReceipt-form ref="form" @ok="getList"></financeInvoiceReceipt-form>
    <goods-invoice-un-write-off ref="goodsInvoiceUnWriteOff" @ok="getList"></goods-invoice-un-write-off>
    <upload-dialog ref="uploadDialog" @ok="getList" @handleFileSuccess="handleFileSuccess"></upload-dialog>
  </div>
</template>

<script>
import {deleteAction, getAction} from '@/api/manage'
import FinanceInvoiceReceiptForm from '@/views/develop/finance/financeInvoiceReceipt/module/FinanceInvoiceReceiptForm'
import UploadDialog from "@/views/upload/UploadDialog.vue";
import GoodsInvoiceUnWriteOff from "@/views/develop/finance/financeInvoiceReceipt/module/GoodsInvoiceUnWriteOff.vue";

export default {
  name: "FinanceInvoiceReceiptList",
  dicts:['finance_receipt_status','finance_receipt_way'],
  components: {
    GoodsInvoiceUnWriteOff,
    UploadDialog,
    FinanceInvoiceReceiptForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      orderList:[],
      customerList:[],
      // 客户回款单表格数据
      dataList: [],
      orderLoading: false,
      customerLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: null,
        customerName: null,
        orderId: null,
        orderCode: null,
        money: null,
        status: null,
        orderByColumn:"create_time",
        isAsc:"desc"
      },
      url: {
        list: '/financeInvoiceReceipt/financeInvoiceReceipt/list',
        remove: '/financeInvoiceReceipt/financeInvoiceReceipt/',
        export: '/financeInvoiceReceipt/financeInvoiceReceipt/export',
      },
      tableMaxHeight: window.innerHeight - 320,
    };
  },
  created() {
    this.getList();
    window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.getTableHeight)
  },
  methods: {
    /** 查询客户回款单列表 */
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.form.handleAdd();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(this.url.export, {
        ...this.queryParams
      }, `financeInvoiceReceipt_${new Date().getTime()}.xlsx`)
    },

    showUploadDialog() {
      this.$refs.uploadDialog.title = "回款单信息导入";
      this.$refs.uploadDialog.tmplName = "回款单信息模板.xlsx";
      this.$refs.uploadDialog.fileName = "回款单信息.xlsx";
      this.$refs.uploadDialog.uploadUrl = "/financeInvoiceReceipt/financeInvoiceReceipt/importData";
      this.$refs.uploadDialog.show();
    },

    handleFileSuccess(response, file, fileList) {
      this.$refs.uploadDialog.open = false;
      this.$refs.uploadDialog.isUploading = false;
      if (response.data.code == "200") {
        this.$alert("导入数据：" + response.data.num + response.data.errorText, "导入结果", { dangerouslyUseHTMLString: true });
      } else {
        this.$alert("导入数据：" + response.data.num + response.data.errorText, "导入结果", { dangerouslyUseHTMLString: true });
      }
      this.getList();
    },

    async searchOrder(queryString) {
      this.orderLoading = true;
      if (queryString) {
        try {
          let params = { "pageNum": 1, "pageSize": 20, "code": queryString };
          getAction("/projectBaseInfo/projectBaseInfo/list", params).then(response => {
            this.orderList = response.rows;
            this.orderLoading = false;
          });

        } catch (error) {
          console.error('Error fetching data:', error);
          this.orderLoading = false;
        }
      } else {
        this.orderList = [];
        this.orderLoading = false;
      }
    },



    async searchCustomer(queryString) {
      this.customerLoading = true;
      if (queryString) {
        let params = {
          "pageNum": 1,
          "pageSize": 20,
          "name": queryString
        };
        getAction("/goodsCustomer/goodsCustomer/list", params).then(response => {
          this.customerList = response.rows;
          this.customerLoading = false;
        });
      } else {
        this.customerList = [];
        this.customerLoading = false;
      }
    },


    handleWriteOff(row){
      this.$refs.goodsInvoiceUnWriteOff.show(row);
    }
  }
};
</script>
